package com.hylanda.entity.name;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.lang.StringUtils;

public class BlackListMgr {

	private Map<String, Object> mapBlackWord = new HashMap<String, Object>();
	private List<Pattern> listBlackRegex = new ArrayList<Pattern>();

	private static BlackListMgr instance = new BlackListMgr();
	
	private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BlackListMgr.class);

	public static BlackListMgr getInstance() {
		return instance;
	}

	public void init(InputStream inputStream, String blackWords) {

		mapBlackWord.clear();
		listBlackRegex.clear();

		addBlackWords(blackWords);
		addBlackFile(inputStream);

		return;
	}

	private void addBlackWords(String blackWords) {

		if (!StringUtils.isEmpty(blackWords)) {
			blackWords = blackWords.replace("，", ",");
			String[] words = blackWords.split(",");
			for (int i = 0; i < words.length; i++) {
				mapBlackWord.put(words[i], null);
			}
			
			logger.info("add usr black name :" + words.length);
		}

		return;
	}

	private void addBlackFile(InputStream inputStream) {
		if (inputStream == null) {
			return;
		}
		BufferedReader reader = null;
		InputStreamReader isr = null;
		try {
			isr =new InputStreamReader(inputStream);
			reader = new BufferedReader(isr);
			String line;
			while ((line = reader.readLine()) != null) {
				// \t ㈱
				if (line.contains("\t")) {
					String[] split = line.split("\t");
					String type = split[0].trim();
					String word = split[1].trim();
					if (type.equals("regex")) {
						try {
							listBlackRegex.add(Pattern.compile(word));
						} catch (PatternSyntaxException pe) {
							pe.printStackTrace();
						}
					} else {
						mapBlackWord.put(word, null);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
					isr.close();
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			

		}
		
		logger.info("black name :" + mapBlackWord.size() + ",blackregex:" + listBlackRegex.size());
	}

	/***
	 * 是否命中黑名单
	 * 
	 * @param word
	 * @return
	 */
	public boolean isBlackWord(String word) {
		if (mapBlackWord.containsKey(word)) {
			return true;
		}
		for (int i = 0; i < listBlackRegex.size(); i++) {
			Pattern pattern = listBlackRegex.get(i);
			Matcher matcher = pattern.matcher(word);
			if (matcher.matches()) {
				return true;
			}
		}
		return false;
	}
}
